package cn.e4j.modular.wx.controller;

import cn.digiwin.wx.utils.CookieUtils;
import cn.digiwin.wx.utils.SecurityUtil;
import cn.digiwin.wx.utils.TicketUtil;
import cn.e4j.config.WxGzhProperties;
import cn.e4j.config.WxProperties;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信所用
 * <p>
 * Created by wenchuan.li on 2017/6/16.
 */
@RestController
@RequestMapping("/api/wx/")
public class WxAuthController {

    @Autowired(required=true)
    WxProperties wxProperties;
    @Autowired
    WxGzhProperties wxGzhProperties;

    /**
     * 服务号、企业号JSSDK认证参数
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = {"jssdk"})
    public ResponseData setJSSDKParamsCfg(HttpServletRequest request, HttpServletResponse response) {
        Map outDto = new HashMap();
        try {
            String _source = CookieUtils.getCookie(request, "_WX_SOURCE");
            //获取临时认证票据
            long timestamp = System.currentTimeMillis() / 1000;
            String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
            String ticket = "", appId = "";
            if (_source.equals("G")) {
                ticket = TicketUtil.getJsTicketGzh();
                appId = wxGzhProperties.getAppid();
            } else {
                ticket = TicketUtil.getJsTicket();
                appId = wxProperties.getCorpId();
            }
            String fullurl = request.getParameter("url");
            //logger.debug("fullurl" + fullurl + "    noncestr" + noncestr + "    ticket" + ticket);

            String tmpStr = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + fullurl;
            String signature = SecurityUtil.sHA1Encode(tmpStr).toLowerCase();

            outDto.put("signature", signature);
            outDto.put("timestamp", timestamp);
            outDto.put("noncestr", noncestr);
            outDto.put("appId", appId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData();
        }
        return new SuccessResponseData(outDto);
    }


}
